package com.woniuxy.microsyslogserver.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.bean.SystemLogBean;
import com.woniuxy.constant.AmqpConst;
import com.woniuxy.microsyslogserver.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Description:
 *
 * @Auther: HanLei
 * @Date: 2021/4/9:16:15
 */
@Component
@Slf4j
public class LogQueueListener {

    @Resource
    private SysLogService sysLogServiceImpl;

    /*
     * Description :   监听LOG_QUEUE队列
     *                 调用服务层接口将消息对象传入
     * ChangeLog : 1. 创建 (2021/4/10 11:44 );
     * @param null
     * @return null
     */
    @RabbitHandler
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = AmqpConst.QueueName.LOG_QUEUE, autoDelete = "false",durable = "true"),
            exchange = @Exchange(value = AmqpConst.ExchangeName.LOG_EXCHANGE, type = ExchangeTypes.DIRECT)
    ))
    public void SimpleReceiver(String mes, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long tag) throws IOException {
        try{
            SystemLogBean systemLogBean = JSON.parseObject(mes, SystemLogBean.class);
            sysLogServiceImpl.insert(systemLogBean);
            log.info("消息消费成功");
        }catch (Exception e) {
            log.error("消息消费失败",e.fillInStackTrace());
            // 重新回到队列
            channel.basicNack(tag, false, true);
        } finally {
            // 确认消费，从队列删除掉，避免重复消费
            channel.basicAck(tag, false);
        }
    }
}
